package com.zsj.job;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsj.config.ConfigBean;
import com.zsj.config.ScheduledCondition;
import com.zsj.mysql.entity.RechargeStatics;
import com.zsj.mysql.service.IDyMobileRechargeService;
import com.zsj.mysql.service.IRechargeStaticsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Description: 日终金额统计
 * @Author:
 * @Date:
 */
@Slf4j
@Component
@Conditional(ScheduledCondition.class)
public class StatisticsAmtJob {

    @Autowired
    private IDyMobileRechargeService rechargeService;

    @Autowired
    private IRechargeStaticsService rechargeStaticsService;

    @Autowired
    private ConfigBean configBean;

    @Scheduled(cron = "0 0 7 * * ?")
    public void dyStatistic() {
        qualityStatistics("");
    }

    public void qualityStatistics(String lastDay) {
        if (!"true".equals(configBean.getBatchSwitch())) {
            log.info("批处理开关为:{}，不执行日终金额统计任务", configBean.getBatchSwitch());
            return;
        }
        LocalDate today = LocalDate.now();
        if (StringUtils.isBlank(lastDay)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            lastDay = today.minusDays(1).format(formatter);
        }
        log.info("开始执行日终金额统计任务，日期:{}", lastDay);
        try {
            log.info("开始删除{}日统计数据", lastDay);
            QueryWrapper<RechargeStatics> removeWrapper = new QueryWrapper<>();
            removeWrapper.eq("finish_date", lastDay);
            boolean removeFlag = rechargeStaticsService.remove(removeWrapper);
            log.info("删除{}日统计数据结果:{}", lastDay, removeFlag);

            String month = lastDay.substring(0, 6);
            log.info("开始统计{}日金额信息", lastDay);
            List<RechargeStatics> staticsList = rechargeService.getAmtStatistic(month, lastDay);
            log.info("{}日统计结果为:{}", lastDay, JSONObject.toJSONString(staticsList));
            boolean flag = rechargeStaticsService.saveBatch(staticsList);
            log.info("保存{}日统计结果为:{}", lastDay, flag);
        } catch (Exception e) {
            log.error("统计异常", e);
        }
        log.info("统计{}的数据任务结束", lastDay);
    }
}
